package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.mapper.UserMapper;
import com.daoliuhe.scaffold.mapper.UserRoleRelationMapper;
import com.daoliuhe.scaffold.model.User;
import com.daoliuhe.scaffold.model.UserRoleRelation;
import com.daoliuhe.scaffold.service.UserRoleRelationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class UserRoleRelationServiceImpl implements UserRoleRelationService {
	
	private static final Logger logger = LoggerFactory.getLogger(UserRoleRelationServiceImpl.class);
	@Autowired
	UserRoleRelationMapper userRoleRelationMapper;
	
	@Autowired
	UserMapper userMapper;

	@Override
	public Object getRolePageData(UserRoleRelation relation) {
		logger.info("getRolePageData,relation:{}",relation);
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userRoleRelationMapper.getRolePageCount(relation);
		map.put("total", total);
		int curPage = relation.getPage();
		int rows = relation.getRows();
		int maxPage = (total + rows - 1) / rows;
		if (curPage > maxPage && maxPage > 0) {
			relation.setPage(maxPage);
		}
		
		map.put("rows", userRoleRelationMapper.getRolePageData(relation));
		return map;
	}
	
	@Override
	public Object getUserPageData(UserRoleRelation relation) {
		logger.info("getUserPageData,relation:{}",relation);
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userRoleRelationMapper.getUserPageCount(relation);
		int curPage = relation.getPage();
		int rows = relation.getRows();
		int maxPage = (total + rows - 1) / rows;
		if (curPage > maxPage && maxPage > 0) {
			relation.setPage(maxPage);
		}
		map.put("total", total);
		map.put("rows", userRoleRelationMapper.getUserPageData(relation));
		return map;
	}
	
	@Override
	public Object saveRelation(UserRoleRelation relation) {
		logger.info("saveRelation,relation:{}",relation);
		Map<String, Object> json = new HashMap<String, Object>();
		boolean success = false;
		String reason = "";
		// 用户id和角色id联合查询
		if (StringUtils.isEmpty(relation.getUserId()) || 
				StringUtils.isEmpty(relation.getRoleId())) {
			reason = "用户或角色不能为空!";
		} else if (userRoleRelationMapper.select(relation).isEmpty()) {
			int result = userRoleRelationMapper.insert(relation);
			if (result == 1) {
				success = true;
			} else {
				reason = "保存失败!";
			}
		} else {
			reason = "已替换!";
		}
		json.put("success", success);
		json.put("reason", reason);
		return json;
	}
	
	@Override
	public Object deleteForUser(String userId, String roleIds) {
		logger.info("deleteForUser,userId:{},roleIds:{}",userId,roleIds);
		Map<String, Object> json = new HashMap<String, Object>();
		boolean success = false;
		String reason = "";
		if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(roleIds)) {
			reason = "参数错误!";
		} else {
			List<String> list = Arrays.asList(roleIds.split(","));
			userRoleRelationMapper.deleteRelationForUser(userId, list);
			success = true;
		}
		
		json.put("success", success);
		json.put("reason", reason);
		return json;
	}
	
	@Override
	public Object deleteForRole(String userIds, String roleId) {
		logger.info("deleteForRole,userIds:{},roleId:{}",userIds,roleId);
		Map<String, Object> json = new HashMap<String, Object>();
		boolean success = false;
		String reason = "";
		if (StringUtils.isEmpty(userIds) || StringUtils.isEmpty(roleId)) {
			reason = "参数错误!";
		} else {
			List<String> list = Arrays.asList(userIds.split(","));
			userRoleRelationMapper.deleteRelationForRole(list, roleId);
			success = true;
		}
		
		json.put("success", success);
		json.put("reason", reason);
		return json;
	}
	
	@Override
	public Object saveBatchUser(String userLoginIds, String roleId) {
		logger.info("saveBatchUser,userLoginIds:{},roleId:{}",userLoginIds,roleId);
		Map<String, Object> json = new HashMap<String, Object>();
		boolean success = false;
		String reason = "";
		if (StringUtils.isEmpty(userLoginIds) || StringUtils.isEmpty(roleId)) {
			reason = "参数错误!";
		} else {
			List<String> loginIds = new ArrayList<String>(Arrays.asList(userLoginIds.split(",")));
			List<User> users = userMapper.getByLoginIds(loginIds);
			List<String> userIds = new ArrayList<String>();
			for (User user : users) {
				loginIds.remove(user.getLoginId());
				userIds.add(user.getId());
			}
			if (loginIds.isEmpty()) {
				List<UserRoleRelation> list = new ArrayList<UserRoleRelation>();
				for (String userId : userIds) {
					UserRoleRelation ur = new UserRoleRelation();
					ur.setUserId(userId);
					ur.setRoleId(roleId);
					
					// 只有未存在数据是才导入
					if (userRoleRelationMapper.select(ur).isEmpty()) {
						list.add(ur);
					}
				}
				if (!list.isEmpty()) {
					userRoleRelationMapper.saveBatchUser(list);
				}
				success = true;
			} else {
				reason = String.format("工号%s在系统中不存在,中断导入!", Arrays.toString(loginIds.toArray()));
			}
		}
		
		json.put("success", success);
		json.put("reason", reason);
		return json;
	}
	
	@Override
	public Object saveBatchRole(String userId, String roleIds) {
		logger.info("saveBatchRole,userId:{},roleIds:{}",userId,roleIds);
		Map<String, Object> json = new HashMap<String, Object>();
		boolean success = false;
		String reason = "";
		if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(roleIds)) {
			reason = "参数错误!";
		} else {
			List<String> roleList = new ArrayList<String>(Arrays.asList(roleIds.split(";")));
			for (String roleId : roleList) {
				UserRoleRelation relation = new UserRoleRelation();
				relation.setUserId(userId);
				relation.setRoleId(roleId);
				if (userRoleRelationMapper.select(relation).isEmpty()) {
					userRoleRelationMapper.insert(relation);
				}
			}
			success = true;
		}
		json.put("success", success);
		json.put("reason", reason);
		return json;
	}
	
	@Override
	public Object saveBatchUserForRole(String userIds, String roleId) {
		logger.info("saveBatchUserForRole,userIds:{},roleId:{}",userIds,roleId);
		Map<String, Object> json = new HashMap<String, Object>();
		boolean success = false;
		String reason = "";
		if (StringUtils.isEmpty(userIds) || StringUtils.isEmpty(roleId)) {
			reason = "参数错误!";
		} else {
			List<String> userList = new ArrayList<String>(Arrays.asList(userIds.split(";")));
			for (String userId : userList) {
				UserRoleRelation relation = new UserRoleRelation();
				relation.setUserId(userId);
				relation.setRoleId(roleId);
				if (userRoleRelationMapper.select(relation).isEmpty()) {
					userRoleRelationMapper.insert(relation);
				}
			}
			success = true;
		}
		json.put("success", success);
		json.put("reason", reason);
		return json;
	}
}
